﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging;
using PMS.Core.Infrastructure;
using PMS.Core.Utils;
using PMS.Web.Framework.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace PMS.Web.Framework.Mvc.ModelBinding
{
    /// <summary>
    /// Represents model binder provider for the creating EntityModelBinderProvider
    /// </summary>
    public class EntityModelBinderProvider : IModelBinderProvider
    {
        private readonly IList<IInputFormatter> _formatters;
        private readonly IHttpRequestStreamReaderFactory _readerFactory;
        private readonly ILoggerFactory _loggerFact;
        /// <summary>
        /// Creates a new <see cref="BodyModelBinderProvider"/>.
        /// </summary>
        /// <param name="formatters">The list of <see cref="IInputFormatter"/>.</param>
        /// <param name="readerFactory">The <see cref="IHttpRequestStreamReaderFactory"/>.</param>
        public EntityModelBinderProvider(IList<IInputFormatter> formatters, IHttpRequestStreamReaderFactory readerFactory)
        {
            _formatters = formatters;
            _readerFactory = readerFactory;
            _loggerFact = EngineContext.Current.Resolve<ILoggerFactory>();
            if (_formatters == null)
            {
                throw new ArgumentNullException(nameof(_formatters));
            }

            if (_readerFactory == null)
            {
                throw new ArgumentNullException(nameof(_readerFactory));
            }
        }

        /// <summary>
        /// Creates a nop model binder based on passed context
        /// </summary>
        /// <param name="context">Model binder provider context</param>
        /// <returns>Model binder</returns>
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));


            var modelType = context.Metadata.ModelType;
            if (!typeof(BaseEntityModel).IsAssignableFrom(modelType))
                return null;

            if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType)
            {
                //DavidLee: try get model from Body Source for ajax post
                BodyModelBinder bodymodelBinder = null;
                if (context.BindingInfo.BindingSource != null &&
                                context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Body))
                {
                    if (_formatters.Count == 0)
                    {
                        throw new PMSException("EntityModelBinderProvider:FormatInputFormattersAreRequired for {0}, {1}, {2}",
                            typeof(MvcOptions).FullName,
                            nameof(MvcOptions.InputFormatters),
                            typeof(IInputFormatter).FullName);
                    }
                    bodymodelBinder = new BodyModelBinder(_formatters, _readerFactory);
                }
                //create binders for all model properties
                var propertyBinders = context.Metadata.Properties
                    .ToDictionary(modelProperty => modelProperty, modelProperty => context.CreateBinder(modelProperty));

                return new EntityModelBinder(propertyBinders, _loggerFact) { BodyModelBinder = bodymodelBinder };
            }

            //or return null to further search for a suitable binder
            return null;
        }
    }

}
